package com.pudu.pudusclient;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.util.Log;

import com.pudu.socketcan.CanBusNative;
import com.pudu.socketcan.CanDataCallback;

import java.util.Arrays;

public class CANDataService extends Service {

    public static String TAG = "CANDataService";

    public static final int MESSAGE_FROM_CAN_SPI = 1;
    public boolean mServiceRunning = false;

    private IBinder binder = new CanDataBinder();
    private Handler mHandler;
    private PumpMessageThread mThread;
    public CanDataHandle mCanDataHandle;
    public CanDataCallback mCanRecCallBack;


    static int mycount = 0;
    @Override
    public void onCreate() {
        mServiceRunning = true;
        mCanRecCallBack = new CanDataCallback() {
            @Override
            public void onCanReceive(byte[] data) {
                Log.i("JinLog", "onCanReceive" + mycount++);
                Log.i("JinLog",bytesToHexString(data));

                if (data != null) {
                    Log.i("time","can receive data:"+ Arrays.toString(data));
                    if(data[0] == 0x01){
                        Log.i("time","can receive speed data:"+Arrays.toString(data));
                        if (data[6] - num6 != 1) {
                            Log.i("time","data delay:"+Arrays.toString(data)+" num:"+(data[6]-num6));
                        }
                        num6 = data[6];
                    }
                }
                if (mHandler != null && data != null ) {
                    mHandler.obtainMessage(MESSAGE_FROM_CAN_SPI, data).sendToTarget();
                    mCanDataHandle.dataFromCan(data);
                    receiveCnt++;
                    CNT++;
                    Log.i("time","all count: " + CNT);
                    if (data[0] == 0x01) {
                        long time = System.currentTimeMillis();
//                        if(time-timeLast >150 || time-timeLast < 50)
                        if (data[6] - numLast != 1 && data[6] - numLast != -255) {
                            Log.i("time", "numErr:" + (data[6] - numLast) + "    CNT:" + CNT + "   time:" + (time - timeLast));
                        }
                        timeLast = time;
                        numLast = data[6];

                        numSPD++;
                        Log.i("time","numSPD"+numSPD);
                    }

                    if (data[0] == 0x07) {
                        Log.i("time", "receive num:" + receiveCnt);
                        receiveCnt = 0;

                        numPlant++;
                        Log.i("time","numPlate"+numPlant);
                    }

                    if (data[0] == 0x03) {
                        numUWB++;
                        Log.i("time","numUWB"+numUWB);
                    }

                    if (data[0] == 0x04 || data[0] == 0x05) {
                        numIRD++;
                        Log.i("time","numIRD"+numIRD);
                    }
                    if (System.currentTimeMillis() - time1s > 1000) {
                        Log.i("time","time1s:"+time1s+" cnt:"+CNT+" spd:"+numSPD+" uwb:"+numUWB+" ird:"+numIRD);
                        time1s = System.currentTimeMillis();
                        numUWB = 0;
                        numSPD = 0;
                        CNT = 0;
                        numIRD = 0;
                    }

                }
            }
        };
        mThread = new PumpMessageThread();
        mThread.mCallback = mCanRecCallBack;
        mThread.start();
    }

    public void CANDataHandleStart() {
        mCanDataHandle =  CanDataHandle.getInstance(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        StopCanDataHandle();
        mServiceRunning = false;
    }

    public void StopCanDataHandle(){
        if(mCanDataHandle != null)
        {
            mCanDataHandle.Exit();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_NOT_STICKY;
    }

    public void write(byte[] data) {
        writeDatatoCanSpi(data);
    }

    long timeLast = System.currentTimeMillis();
    int CNT = 0;
    int receiveCnt = 0;
    int numLast = 0;
    int num6 = 0;
    int numUWB = 0;
    int numSPD = 0;
    int numPlant = 0;
    int numIRD = 0;
    long time1s = 0;
    public class PumpMessageThread extends Thread {
        CanDataCallback mCallback;
        @Override
        public void run() {
            CanBusNative.startReceive(mCallback);
        }
    }

    public class CanDataBinder extends Binder {
        public CANDataService getService() {
            return CANDataService.this;
        }
    }

    public void setHandler(Handler mHandler) {
        this.mHandler = mHandler;
    }

    public void writeDatatoCanSpi(byte[] data) {
        CanBusNative.sendBytes(data);
    }



    @NonNull
    public static final String bytesToHexString(byte[] bArray){
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}
